
package controllers;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import models.Playlist;
import models.User;
import play.cache.Cache;
import play.libs.Codec;
import play.libs.Crypto;
import play.libs.Images;
import play.mvc.Controller;

public class Security extends Controller {

	static boolean checkAccess(User owner) {
		if (!session.contains("username")) {
			return false;
		}
		String username = session.get("username");
		if (owner.name.equals(username))
			return true;
		return false;
	}

	static void checkLogged() {
		if (!session.contains("username")) {
			renderTemplate("errors/not_logged");
		}
	}

	static boolean isLogged() {
		return session.contains("username");
	}

	static String getUserName() {
		return session.contains("username") ? session.get("username") : "";
	}

	static User getLoggedUser() {
		if (!session.contains("username"))
			return null;
		User u = User.find("byName", session.get("username")).first();
		return u;
	}

	public static void logout() {
		session.clear();
		//response.removeCookie("rememberme");
		Map<String, String> map = new HashMap<String, String>();
		map.put("success", "success");
		renderJSON(map);
	}

	public static void login(String name, String password) {
		List<User> us = User.find("byName", name).fetch();
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", name);
		if (us.isEmpty()) {
			map.put("nameerr", "true");
			renderJSON(map);
		}
		User u = us.get(0);
		if (u != null && !Crypto.passwordHash(password).equals(u.password)) {
			map.put("passworderr", "true");
			renderJSON(map);
		}
		session.put("username", name);
		map.put("success", "success");
		renderJSON(map);
	}

	public static void capcha(String id) {
		Images.Captcha captcha = Images.captcha();
		String code = captcha.getText("#E4EAFD");
		Cache.set(id, code, "10mn");
		renderBinary(captcha);
	}

	public static void signupform() {
		addCapchaAndRender(new HashMap<String, String>());
	}

	public static void signup(String name, String password, String capchatext, String capchaid) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", name);
		String realCt = (String) Cache.get(params.get("capchaid"));
		boolean good = true;
		if (!capchatext.equals(realCt)) {
			map.put("capchaerr", "true");
			good = false;
		}
		if (!User.find("byName", name).fetch().isEmpty()) {
			map.put("nameerr", "true");
			good = false;
		}
		if (good) {
			User u = new User();
			u.name = name;
			u.password = Crypto.passwordHash(password);
			u.save();
			Playlist p = new Playlist();
			p.name = "Likes";
			p.user = u;
			p.save();
			p = new Playlist();
			p.name = "Dislikes";
			p.user = u;
			p.save();
			map.put("success", "success");
			login(name, password);
			renderJSON(map);
		}
		addCapchaAndRender(map);
	}

	static void addCapchaAndRender(Map<String, String> map) {
		String randomID = Codec.UUID();
		map.put("capchaid", randomID);
		renderJSON(map);
	}
}
